<script setup lang="ts">
defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "Menu"
});
import { ref, reactive } from "vue";
import { Calendar, Search } from "@element-plus/icons-vue";
import { itemList, addItem, delItem } from "@/api/menu";
import { type DataInfo, setToken, removeToken } from "@/utils/auth";
import { json } from "stream/consumers";
import { func } from "vue-types";
import { addDialog } from "@/components/ReDialog";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { ElNotification } from "element-plus";
function GetTreeData(data) {
  let TreeData = [];
  let map = new Map(); //存在id,对应所在的内存地址
  // console.log(map);
  let outputObj, pid;
  for (let i = 0; i < data.length; i++) {
    pid = data[i].pid;
    if (map.has(pid)) {
      //存在，将些信息，加入到对应id=pid的对象上的children
      if (!map.get(pid).children) map.get(pid).children = [];
      let obj = new Object(data[i]);
      map.get(pid).children.push(obj);
      map.set(data[i].id, obj);
      // console.log(map);
    } else if (!map.has(pid) && pid == 0) {
      //这里处理pid不存在，且pid 为0的处理，pid不存在，且不为0的，程序不考虑这种情况
      outputObj = new Object(data[i]);
      TreeData.push(outputObj);
      map.set(data[i].id, outputObj);
      // console.log(map);
    }
  }
  return TreeData;
  console.log(map);
}
function typechild(data) {
  for (let item of data) {
    if (item.children) {
      if (item.type == 1) {
        item.type = "菜单";
      } else {
        item.type = "功能";
      }
      typechild(item.children);
    } else {
      if (item.type == 1) {
        item.type = "菜单";
      } else {
        item.type = "功能";
      }
    }
  }
  return data;
}

// 菜单列表请求
const tableData = ref();
renders();
function renders() {
  new Promise((resolve, reject) => {
    itemList()
      .then(data => {
        console.log(JSON.parse(data));
        tableData.value = GetTreeData(JSON.parse(data).data);
        console.log(tableData.value);
        tableData.value = typechild(tableData.value);
      })
      .catch(error => {
        reject(error);
      });
  });
}
// 菜单选项
const mneuName = ref("");
const status = ref();
const options = [
  {
    status: "菜单",
    label: "菜单"
  },
  {
    status: "功能",
    label: "功能"
  }
];

const columns: TableColumnList = [
  {
    label: "序号",
    prop: "id"
  },
  {
    label: "页面标题",
    prop: "title"
  },
  {
    label: "路径",
    prop: "path"
  },
  {
    label: "图标",
    prop: "icon"
  },
  {
    label: "类型",
    prop: "type"
  },
  {
    label: "排序",
    prop: "sort"
  },
  {
    label: "操作",
    slot: "button"
  }
];

const form = reactive({
  topmneu: "",
  title: "",
  local: "",
  icon: "",
  diff: "0",
  sort: 0
});
function clearVal() {
  form.topmneu = "";
  form.icon = "";
  form.local = "";
  form.title = "";
  form.diff = "0";
  form.sort = 0;
}
let chongzhi = () => {
  clearVal();
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 800);
  renders();
  mneuName.value = "";
  status.value = "";
};
let addon = () => {
  clearVal();
  dialogFormVisible.value = true;
  opstatus.value = 1;
  console.log(opstatus.value);
};
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const modelTitle = ref("添加菜单");
// 表单校验

const ruleFormRef = ref(null);
const rules = ref({
  topmneu: [{ required: true, message: "请完善上级菜单", trigger: "change" }],
  title: [{ required: true, message: "请完善菜单标题", trigger: "blur" }],
  local: [{ required: true, message: "请完善菜单路径", trigger: "blur" }],
  icon: [{ required: true, message: "请完善菜单图标", trigger: "blur" }],
  diff: [{ required: true, message: "不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "请排序", trigger: "blur" }]
});

// 添加/编辑状态
const opstatus = ref(0);
// 编辑按钮
const efitid = ref();
function showinfo(data) {
  for (let item of data) {
    if (item.children) {
      if (item.id == efitid.value) {
        form.topmneu = item.pid;
        form.icon = item.icon;
        form.local = item.path;
        form.title = item.title;
        form.diff = item.type == "菜单" ? "1" : "2";
        form.sort = item.sort;
      }
      showinfo(item.children);
    } else {
      if (item.id == efitid.value) {
        form.topmneu = item.pid;
        form.icon = item.icon;
        form.local = item.path;
        form.title = item.title;
        form.diff = item.type == "菜单" ? "1" : "2";
        form.sort = item.sort;
      }
    }
  }
}
let editbox = edid => {
  clearVal();
  dialogFormVisible.value = true;
  efitid.value = edid;
  opstatus.value = 2;
  showinfo(tableData.value);
  console.log(opstatus.value);
};
// 菜单添加
let addMneu = () => {
  console.log(ruleFormRef.value);
  console.log(form);

  ruleFormRef.value.validate(valid => {
    console.log(valid);

    // 不通过校验
    if (!valid) return ElMessage.error("请将内容填写完成后 再进行添加操作!");
    if (opstatus.value == 1) {
      let addobj = {
        pid: form.topmneu,
        icon: form.icon,
        path: form.local,
        title: form.title,
        type: form.diff,
        sort: form.sort
      };
      addItem(addobj)
        .then(data => {
          console.log(JSON.parse(data));
          if (JSON.parse(data).code == 1) {
            renders();
            ElNotification({
              title: "Success",
              message: "添加成功",
              type: "success"
            });
            dialogFormVisible.value = false;
            loading.value = true;
            setTimeout(() => {
              loading.value = false;
            }, 800);
          } else {
            ElNotification({
              title: "Error",
              message: "操作失败",
              type: "error"
            });
          }
        })
        .catch(error => {
          console.log(error);
        });
      console.log(addobj);
    } else {
      let editobj = {
        id: efitid.value,
        pid: form.topmneu,
        icon: form.icon,
        path: form.local,
        title: form.title,
        type: form.diff,
        sort: form.sort
      };
      addItem(editobj)
        .then(data => {
          console.log(JSON.parse(data));
          if (JSON.parse(data).code == 1) {
            renders();
            ElNotification({
              title: "Success",
              message: "操作成功",
              type: "success"
            });
            dialogFormVisible.value = false;
            loading.value = true;
            setTimeout(() => {
              loading.value = false;
            }, 800);
          } else {
            ElNotification({
              title: "Error",
              message: "操作失败",
              type: "error"
            });
          }
        })
        .catch(error => {
          console.log(error);
        });
      console.log(editobj);
    }
  });
};

const num = ref(1);
const handleChange = (value: number) => {
  console.log(value);
};

// 加载效果
const loading = ref(false);

// 删除按钮
const delid = ref();
const centerDialogVisible = ref(false);
let delsure = elid => {
  centerDialogVisible.value = true;
  console.log(elid);
  delid.value = elid;
};

// 确认删除
let delyes = () => {
  centerDialogVisible.value = false;
  delItem({ id: delid.value })
    .then(data => {
      console.log(JSON.parse(data));
      if (JSON.parse(data).code == 1) {
        renders();
        ElNotification({
          title: "Success",
          message: "操作成功",
          type: "success"
        });
        loading.value = true;
        setTimeout(() => {
          loading.value = false;
        }, 800);
      } else {
        ElNotification({
          title: "Error",
          message: "操作失败",
          type: "error"
        });
      }
    })
    .catch(error => {
      console.log(error);
    });
};

let searchinp = () => {
  let datas = tableData.value;
  tableData.value = datas.filter(function (item) {
    if (String(item.title).indexOf(String(mneuName.value)) > -1) {
      loading.value = true;
      setTimeout(() => {
        loading.value = false;
      }, 1200);
      return item;
    } else {
      loading.value = true;
      setTimeout(() => {
        loading.value = false;
      }, 1200);
      tableData.value = "";
    }
  });
};
let shanxuan = () => {
  let datas = tableData.value;
  tableData.value = datas.filter(function (item) {
    if (String(item.type).indexOf(String(status.value)) > -1) {
      loading.value = true;
      setTimeout(() => {
        loading.value = false;
      }, 1200);
      return item;
    } else {
      loading.value = true;
      setTimeout(() => {
        loading.value = false;
      }, 1200);
      tableData.value = "";
    }
  });
};
</script>

<template>
  <div class="pagebg">
    <h1>菜单管理</h1>
    <!-- 输入框 -->
    <div class="searchbox">
      <div>
        <el-input
          style="width: 240px; margin-right: 20px"
          v-model="mneuName"
          placeholder="请输入菜单名称"
          :suffix-icon="Search"
          @input="searchinp"
        />
        <el-select
          v-model="status"
          clearable
          placeholder="请选择菜单类型"
          style="width: 240px"
          @change="shanxuan"
        >
          <el-option
            v-for="(item, index) in options"
            :key="index"
            :label="item.label"
            :value="item.status"
          />
        </el-select>
        <el-button style="margin-left: 10px" @click="chongzhi">重置</el-button>
      </div>
      <!-- 新增按钮 -->
      <div>
        <el-button type="primary" @click="addon">新增</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div>
      <pure-table
        :data="tableData"
        :columns="columns"
        row-key="id"
        border
        default-expand-all
        class="mb-6"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        v-loading="loading"
      >
        <template #button="scope">
          <el-button type="primary" @click="editbox(scope.row.id)"
            >编辑</el-button
          >
          <el-button type="danger" @click="delsure(scope.row.id)"
            >删除</el-button
          >
        </template>
      </pure-table>
    </div>

    <!-- 添加、编辑 弹窗 -->

    <el-dialog v-model="dialogFormVisible" :title="modelTitle">
      <el-form :model="form" :rules="rules" ref="ruleFormRef">
        <el-form-item
          label="上级菜单"
          :label-width="formLabelWidth"
          prop="topmneu"
        >
          <el-tree-select
            v-model="form.topmneu"
            :data="tableData"
            :props="{ label: 'title', value: 'id' }"
            :render-after-expand="false"
            style="width: 100%"
            check-strictly
          />
        </el-form-item>
        <el-form-item
          label="菜单标题"
          :label-width="formLabelWidth"
          prop="title"
        >
          <el-input
            v-model="form.title"
            autocomplete="off"
            placeholder="请选择菜单标题"
          />
        </el-form-item>
        <el-form-item
          label="菜单路径"
          :label-width="formLabelWidth"
          prop="local"
        >
          <el-input
            v-model="form.local"
            autocomplete="off"
            placeholder="请选择菜单路径"
          />
        </el-form-item>
        <el-form-item
          label="菜单图标"
          :label-width="formLabelWidth"
          prop="icon"
        >
          <el-input
            v-model="form.icon"
            autocomplete="off"
            placeholder="请选择菜单图标"
          />
        </el-form-item>
        <el-form-item label="是否菜单" style="margin-left: 64px" prop="diff">
          <el-radio-group v-model="form.diff">
            <el-radio label="1">菜单</el-radio>
            <el-radio label="2">功能</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="菜单排序"
          :label-width="formLabelWidth"
          prop="sort"
        >
          <!-- autocomplete="off"  -->
          <el-input-number
            v-model="form.sort"
            :min="0"
            :max="10"
            controls-position="right"
            size="large"
            style="width: 100%; height: 35px"
            @change="handleChange"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addMneu"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认删除弹窗 -->
    <el-dialog v-model="centerDialogVisible" title="Warning" width="30%" center>
      <span> 确定删除当前菜单吗？ </span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="delyes"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style>
h1 {
  font-weight: 400;
}
.grow {
  padding: 0;
}
.pagebg {
  width: auto;
  height: 100%;
  background-color: #ffffff;
}
.searchbox {
  width: auto;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
